/**
 * 
 */
package com.attilax.io;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import com.attilax.exception.ExUtil;

/**
 * @author attilax 2016年9月27日 下午6:54:25
 */
public class StreamUtil {

	/**
	 * attilax 2016年9月27日 下午6:54:25
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public static void streamEx(InputStream inStream, OutputStream outStream) {
		int bytesum = 0;
		// int byteread = 0;
		try {
			int byteread;
			byte[] buffer = new byte[1204];
			int length;
			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread;
				// System.out.println(bytesum);
				outStream.write(buffer, 0, byteread);
			}
			outStream.flush();
		} catch (Exception e) {
			ExUtil.throwExV2(e);
		}

		try {
			inStream.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			outStream.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * attilax 2016年9月28日 上午12:57:40
	 * 
	 * @param inputStream
	 */
	public static void flushNclose(InputStream inputStream) {
		 		try {
			if (inputStream != null)
				inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void flushNclose(OutputStream os) {
		try {
			if (os != null)
				os.flush();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			if (os != null)
				// if(os.)
				os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	ByteArrayOutputStream StrOutStream = new ByteArrayOutputStream();
	PrintStream stdOut = System.out;// 保存标准输出流

	 

	public void restoreStdOut() {
		System.setOut(stdOut);

	}

	public String getStr() {
		byte[] buf = StrOutStream.toByteArray();
		return new String(buf);
	}

	public PrintStream RedirectToStrOut() {
		stdOut = System.out;// 保存标准输出流

		PrintStream ps = new PrintStream(StrOutStream);
	 
		System.setOut( ps);
		return null;
	}

}
